extends Control


@onready var file_dialog: FileDialog = $FileDialog as FileDialog
@onready var line_edit_folder: LineEdit = $LineEditFolder as LineEdit
@onready var line_edit_file_filter: LineEdit = $LineEditFileFilter as LineEdit
@onready var text_edit_find_result: TextEdit = $TextEditFindResult as TextEdit
@onready var text_edit_merge_result: TextEdit = $TextEditMergeResult as TextEdit


# 选择目录事件
func _on_button_select_folder_pressed() -> void:
	var current_folder: String = line_edit_folder.text
	if not current_folder.is_empty():
		file_dialog.current_dir = current_folder
	file_dialog.show()
	

# 选择目录后的事件
func _on_file_dialog_dir_selected(dir: String) -> void:
	line_edit_folder.text = dir


# 查找事件
func _on_button_find_pressed() -> void:
	var dir: String = line_edit_folder.text
	if dir.is_empty() or not DirAccess.dir_exists_absolute(dir):
		return
	var filter: String = line_edit_file_filter.text
	var files: Array[String] = []
	_find_files(dir, filter, files)
	_show_files(files)


# 合并事件
func _on_button_merge_pressed() -> void:
	var result: String = _merge_content()
	text_edit_merge_result.text = result


# 查找文件
func _find_files(dir: String, filter: String, files: Array[String]) -> void:
	var fs: PackedStringArray = DirAccess.get_files_at(dir)
	if fs and not fs.is_empty():
		var is_filter_empty: bool = filter.is_empty()
		for file: String in fs:
			if is_filter_empty or file.matchn(filter):
				files.append("{0}/{1}".format([ dir, file ]))
	var sub_dirs: PackedStringArray = DirAccess.get_directories_at(dir)
	if sub_dirs and not sub_dirs.is_empty():
		for sub_dir: String in sub_dirs:
			_find_files("{0}/{1}".format([ dir, sub_dir ]), filter, files)


# 显示查找到的文件
func _show_files(files: Array[String]) -> void:
	var result: String = ""
	if files and not files.is_empty():
		result = "\n".join(files)
	text_edit_find_result.text = result
	
	
# 合并文件的内容
func _merge_content() -> String:
	var result: String = text_edit_find_result.text
	if result.is_empty():
		return ""
	var files: PackedStringArray = result.split("\n", false)
	if not files or files.is_empty():
		return ""
	var contents: Array[String] = []
	for file: String in files:
		var content: String = FileAccess.get_file_as_string(file)
		contents.append("# {0}\n{1}".format([ file, content ]))
	return "\n\n".join(contents)
